<template>
  <div class="conversation-stats-container">
    <div class="page-header">
      <h2>谈话统计分析</h2>
      <p>分析谈话记录数据，提供统计报表</p>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="谈话主题">
            <el-input 
              v-model="filterForm.title" 
              placeholder="请输入谈话主题" 
              clearable
              style="width: 180px"
              @change="handleFilterChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilter">
              <el-icon><Search /></el-icon> 应用筛选
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-blue">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalCount }}</div>
              <div class="stat-label">谈话总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-green">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.userCount }}</div>
              <div class="stat-label">谈话对象人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-orange">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.avgDuration }}分钟</div>
              <div class="stat-label">平均谈话时长</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-purple">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.recentDays }}</div>
              <div class="stat-label">最近一次谈话(天)</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>谈话主题分布</span>
            </div>
          </template>
          <div class="chart-container" id="typeChart" ref="typeChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>谈话数量趋势</span>
            </div>
          </template>
          <div class="chart-container" id="trendChart" ref="trendChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 谈话主题详细统计 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="table-header">
          <span>谈话主题详细统计</span>
          <el-button type="primary" size="small" @click="exportToExcel">
            <el-icon><Download /></el-icon> 导出Excel
          </el-button>
        </div>
      </template>
      <el-table :data="typeStatsData" border style="width: 100%">
        <el-table-column prop="type" label="谈话主题" />
        <el-table-column prop="count" label="谈话数量" width="120" align="center" />
        <el-table-column prop="percent" label="占比" width="120" align="center">
          <template #default="scope">
            {{ scope.row.percent }}%
          </template>
        </el-table-column>
        <el-table-column prop="avgDuration" label="平均时长(分钟)" width="150" align="center" />
        <el-table-column prop="userCount" label="涉及人数" width="120" align="center" />
      </el-table>
    </el-card>

    <!-- 最近谈话记录 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="table-header">
          <span>最近谈话记录</span>
          <el-button type="primary" size="small" @click="goToList">
            <el-icon><Right /></el-icon> 查看全部
          </el-button>
        </div>
      </template>
      <el-table :data="recentConversations" border style="width: 100%">
        <el-table-column prop="name" label="谈话对象" min-width="100" />
        <el-table-column prop="result" label="谈话主题" min-width="150" />
        <el-table-column prop="date" label="谈话日期" min-width="120" />
        <el-table-column prop="duration" label="时长(分钟)" width="100" align="center" />
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="谈话详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="谈话对象">{{ currentConversation.name }}</el-descriptions-item>
        <el-descriptions-item label="谈话主题">{{ currentConversation.result }}</el-descriptions-item>
        <el-descriptions-item label="谈话日期">{{ currentConversation.date }}</el-descriptions-item>
        <el-descriptions-item label="谈话地点">{{ currentConversation.location || '-' }}</el-descriptions-item>
        <el-descriptions-item label="谈话内容" :span="2">
          <div class="conversation-content">
            {{ currentConversation.content || '暂无内容' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentConversation.fileUrl" label="谈话记录附件" :span="2">
          <div class="file-preview">
            <el-image 
              :src="currentConversation.fileUrl" 
              :preview-src-list="[currentConversation.fileUrl]"
              fit="contain"
              style="max-width: 100%; max-height: 300px; cursor: pointer;"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <div>图片加载失败</div>
                </div>
              </template>
            </el-image>
            <div class="image-tip">点击图片可全屏查看</div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { 
  Search, Refresh, ChatDotRound, User, Calendar, 
  Timer, Download, Right, View, Picture
} from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import { getConversationList } from '@/api/conversation';

const router = useRouter();

// 筛选表单
const filterForm = reactive({
  title: ''
});

// 统计数据
const statsData = reactive({
  totalCount: 0,
  userCount: 0,
  avgDuration: 0,
  recentDays: 0
});

// 谈话类型统计数据
const typeStatsData = ref([]);

// 最近谈话记录
const recentConversations = ref([]);

// 详情对话框
const dialogVisible = ref(false);
const currentConversation = ref({});

// 图表引用
const typeChartRef = ref(null);
const trendChartRef = ref(null);
let typeChart = null;
let trendChart = null;

// 初始化
onMounted(() => {
  // 加载数据
  fetchStatsData();
  
  // 监听窗口大小变化，用于图表自适应
  window.addEventListener('resize', handleResize);
});

// 获取统计数据
const fetchStatsData = async () => {
  try {
    // 构建查询参数
    const queryData = {
      title: filterForm.title
    };
    
    // 获取分页列表，用于统计信息
    const response = await getConversationList(queryData, 1, 50); // 获取更多数据用于统计
    console.log('列表响应:', response.data);
    
    if (response.data.code === 200) {
      const records = response.data.data.page.records || [];
      statsData.totalCount = response.data.data.page.total || 0;
      
      // 处理谈话记录数据
      const mappedRecords = records.map(item => ({
        id: item.id,
        name: item.nickName || '',
        type: item.talkType || 'other',
        interviewer: item.userId || '',
        date: item.talkTime || '',
        location: item.talkPlace || '',
        duration: item.talkDuration || 60,
        content: item.talkSummary || '',
        result: item.talkTitle || '',
        fileUrl: item.fileUrl || ''
      }));
      
      // 获取最近的几条记录
      recentConversations.value = mappedRecords.slice(0, 5);
      
      // 计算平均谈话时长和谈话对象人数
      let totalDuration = 0;
      const uniqueNames = new Set();
      
      mappedRecords.forEach(item => {
        if (item.duration) {
          totalDuration += item.duration;
        }
        console.log(item);
        if (item.name) {
          uniqueNames.add(item.name);
        }
      });
      
      statsData.avgDuration = mappedRecords.length ? Math.round(totalDuration / mappedRecords.length) : 0;
      statsData.userCount = uniqueNames.size;
      
      // 计算最近一次谈话距今的天数
      if (mappedRecords.length > 0) {
        const latestRecord = mappedRecords.reduce((latest, current) => {
          if (!latest.date) return current;
          if (!current.date) return latest;
          
          const currentDate = new Date(current.date);
          return !latest.date || currentDate > new Date(latest.date) ? current : latest;
        }, {});
        
        if (latestRecord.date) {
          const latestDate = new Date(latestRecord.date);
          const today = new Date();
          const timeDiff = today - latestDate;
          statsData.recentDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        }
      }
      
      // 进行前端简单统计
      const topicCount = {};
      const topicDuration = {};
      const topicUsers = {};
      
      mappedRecords.forEach(item => {
        const topic = item.result || '未分类';
        
        // 统计各主题数量
        topicCount[topic] = (topicCount[topic] || 0) + 1;
        
        // 统计各主题时长
        if (item.duration) {
          topicDuration[topic] = (topicDuration[topic] || 0) + item.duration;
        }
        
        // 统计各主题用户
        if (!topicUsers[topic]) topicUsers[topic] = new Set();
        if (item.name) {
          topicUsers[topic].add(item.name);
        }
      });
      
      // 构建主题统计数据
      typeStatsData.value = Object.keys(topicCount).map(topic => {
        const count = topicCount[topic];
        const percent = Math.round((count / statsData.totalCount) * 1000) / 10;
        const avgDuration = count ? Math.round(topicDuration[topic] / count) : 0;
        const userCount = topicUsers[topic].size;
        
        return { type: topic, count, percent, avgDuration, userCount };
      });
    
    // 初始化图表
    nextTick(() => {
      initTypeChart();
      initTrendChart();
    });
    } else {
      ElMessage.error(response.data.msg || '获取谈话记录统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取统计数据失败，请稍后重试');
  }
};

// 初始化谈话主题分布图表
const initTypeChart = () => {
  if (typeChart !== null) {
    typeChart.dispose();
  }
  
  typeChart = echarts.init(typeChartRef.value);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: typeStatsData.value.map(item => item.type)
    },
    series: [
      {
        name: '谈话主题',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: typeStatsData.value.map(item => ({
          value: item.count,
          name: item.type
        })),
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  };
  
  typeChart.setOption(option);
};

// 初始化谈话数量趋势图表
const initTrendChart = () => {
  if (trendChart !== null) {
    trendChart.dispose();
  }
  
  trendChart = echarts.init(trendChartRef.value);
  
  // 模拟月度数据
  const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
  const data = [5, 8, 10, 12, 15, 8];
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '谈话数量',
        type: 'bar',
        barWidth: '60%',
        data: data,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  };
  
  trendChart.setOption(option);
};

// 处理窗口大小变化
const handleResize = () => {
  if (typeChart) {
    typeChart.resize();
  }
  if (trendChart) {
    trendChart.resize();
  }
};

// 处理筛选条件变化
const handleFilterChange = () => {
  // 在应用筛选时再获取数据
};

// 应用筛选
const applyFilter = () => {
  fetchStatsData();
};

// 重置筛选
const resetFilter = () => {
  filterForm.title = '';
  
  fetchStatsData();
};

// 导出Excel
const exportToExcel = () => {
  ElMessage.success('统计数据已导出到Excel');
};

// 获取谈话类型名称
const getTypeName = (type) => {
  const types = {
    motivation: '入党动机谈话',
    report: '思想汇报谈话',
    development: '发展谈话',
    regular: '转正谈话',
    other: '其他谈话'
  };
  return types[type] || type;
};

// 查看详情
const viewDetail = (row) => {
  currentConversation.value = { ...row };
  dialogVisible.value = true;
};

// 跳转到谈话记录列表
const goToList = () => {
  router.push('/conversation/list');
};
</script>

<style scoped>
.conversation-stats-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  margin-bottom: 20px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 30px;
  color: white;
}

.bg-blue {
  background-color: #409EFF;
}

.bg-green {
  background-color: #67C23A;
}

.bg-orange {
  background-color: #E6A23C;
}

.bg-purple {
  background-color: #909399;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.conversation-content, .conversation-result {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.file-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
  }
}
</style> 